package com.rency.ues.webapp.controller;

import com.rency.ues.webapp.common.BaseAction;
import com.rency.ues.webapp.common.Constants;
import com.rency.ues.webapp.common.WebProperty;
import org.apache.commons.lang.StringUtils;
import org.rency.common.utils.domain.SYSDICT;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author: Created by user_rcy@163.com on 2016/08/02.
 * @version: V1.0.0
 * @since JDK 1.8
 */
@Controller
@RequestMapping("/")
public class IndexController extends BaseAction{

    @Resource(name="webProperty")
    private WebProperty webProperty;

    @RequestMapping(value="index.htm",method= RequestMethod.GET)
    public ModelAndView index(){
        return this.view(Constants.VM_PATH_PREFIX_MAIN,"index");
    }

    @RequestMapping(value="login.htm",method= RequestMethod.GET)
    public ModelAndView login(HttpServletRequest req, @RequestHeader HttpHeaders headers){
        String referer = String.valueOf(headers.get("Referer"));
        logger.debug("请求登录, 请求来源:[{}].",referer);
        respBody.setMessage("");
        return this.view(Constants.VM_PATH_PREFIX_LOGIN, "login");
    }

    @RequestMapping(value="logon.htm",method = RequestMethod.POST)
    public ModelAndView logon(HttpServletRequest req, HttpSession session, @RequestHeader HttpHeaders headers){
        String referer = String.valueOf(headers.get("Referer"));
        String userName = req.getParameter("userName");
        logger.info("来自[{}]的用户[{}]请求登录.",referer,userName);
        String password = req.getParameter("password");
        if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
            respBody.setMessage("用户名密码不能为空");
            return this.view(Constants.VM_PATH_PREFIX_LOGIN, "login");
        }
        if(userName.equals(webProperty.getUserName()) && password.equals(webProperty.getPassword())){
            session.setAttribute(SYSDICT.SESSION_USER_KEY,userName);
            return this.redirect(Constants.URL_HOME);
        }else {
            respBody.setMessage("用户名密码不正确");
            return this.view(Constants.VM_PATH_PREFIX_LOGIN, "login");
        }
    }

    @RequestMapping(value="logout.htm")
    public ModelAndView logout(HttpServletRequest req, HttpSession session){
        this.clear();
        session.removeAttribute(SYSDICT.SESSION_USER_KEY);
        return this.redirect(Constants.URL_HOME);
    }

    @RequestMapping(value="404.htm")
    public ModelAndView pageNotFound(HttpServletRequest req, HttpSession session){
        return this.view(Constants.VM_PATH_PREFIX_ERROR,"404");
    }

}
